navbarController.$inject = ['navMenuService','$http','$location','$scope','$rootScope'];
var io = require('socket.io-client');
var constant = require('../../config/constant.config');

function navbarController(navMenuService,$http,$location,$scope,$rootScope) {
    // alert('nav bar ctrl');
    var vm = this;
    vm.user = JSON.parse(sessionStorage.user);
    vm.menus = navMenuService.getMenus();

    //socket
    $rootScope.pendingCountStatus=1;
    var socketConfig = {
        path:constant.CONTEXT_PATH+'socketio'
    }
    var socket = io.connect(location.origin,socketConfig);

    var pendindCount = 0;
    sessionStorage.pc = pendindCount;
    socket.on('ac',function(data){
        console.log('From Server:'+JSON.stringify(data)+',datapc->'+data.pc);
        pendindCount =data.pc;
        sessionStorage.pc = pendindCount;
        $rootScope.pendingCountStatus = 1;
    });

    setInterval(function(){
        var u = sessionStorage.user;
        if(!u){
            clearInterval(this);
            return;
        }
        if($rootScope.pendingCountStatus==0){
            console.log('send to server socket!');
            socket.emit('ac',{modify:true});
            sessionStorage.pc = 0;
        }
    },1000);

    //sign out
    vm.signOut = function(){
        $http.get('/O2OAdministrator/api/signout')
            .then(function (res) {
                console.log(res.data);
                if(res.data.result){
                    sessionStorage.removeItem('user');
                    socket.disconnect();
                    $location.path('/');
                }
            });
    }
}

module.exports = navbarController;